import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaTop, WeaTab, WeaRightMenu, WeaNewScroll, WeaTable, WeaFormItem, WeaSearchGroup, WeaDialog, WeaLocaleProvider, WeaBrowser } from 'ecCom';
import { Button } from 'antd';
import { WeaTableNew, WeaForm, WeaSwitch } from 'comsMobx';
import { toJS } from 'mobx';
import AdSearches from '../public/AdSearches';
import Collapse from './collapse/collapse.js';
import OdocNoRightComponent from "./common/OdocNoRightComponent";

const getLabel = WeaLocaleProvider.getLabel;
const WeaTableMobx = WeaTableNew.WeaTable;
@inject('sendDoc')
@observer
class SendDoc extends React.Component {
  componentDidMount () {
    const { sendDoc, location } = this.props;
    sendDoc.postWebSendDocCondition();
    const isInnerChange = location.query.isInnerChange ? location.query.isInnerChange : '0';
    sendDoc.setMobxState({ isInnerChange });
    sendDoc.initData({
      compParams: {
        viewcondition: 0,
        viewconditiondomkey: 'state',
        isInnerChange,
        state: 0,
      },
    });
  }

  componentWillReceiveProps (nextProps) {
    const { sendDoc, location } = this.props;
    const { postWebSendDocCondition, setMobxState, initData } = sendDoc;
    if (nextProps.location.query.isInnerChange !== location.query.isInnerChange) {
      postWebSendDocCondition();
      const isInnerChange = nextProps.location.query.isInnerChange ? nextProps.location.query.isInnerChange : '0';
      setMobxState({ isInnerChange });
      initData({
        compParams: {
          viewcondition: 0,
          viewconditiondomkey: 'state',
          isInnerChange,
          state: 0,
        },
      });
    }
  }

  componentWillUnmount () {
    const { sendDoc } = this.props;
    sendDoc.setMobxState({
      adSearchForm: new WeaForm(),
      selectRowId: [],
    });
  }

  getSearchs = () => {
    const { status, odocSendDocDialogForm } = this.props.sendDoc;
    let { condition } = toJS(status);
    if (!condition) condition = [];
    const { isFormInit } = odocSendDocDialogForm;
    let group = [];
    isFormInit &&
      condition.map((c, index) => {
        let items = [];
        c.items.map((field) => {
          items.push({
            com: (
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@vkc1hh@${field.domkey[0]}`}
                label={`${field.label}`}
                labelCol={{ span: `${field.labelcol}` }}
                wrapperCol={{ span: `${field.fieldcol}` }}
              >
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@efanjs@${field.domkey[0]}`}
                  fieldConfig={field}
                  form={odocSendDocDialogForm}
                />
              </WeaFormItem>
            ),
            colSpan: 1,
          });
        });
        group.push(
          <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@h4u838@${index}`}
            needTigger={true}
            title={c.title}
            showGroup={c.defaultshow}
            items={items}
            col={1}
          />,
        );
      });
    return group;
  };

  getButton = () => {
    const { sendDoc } = this.props;
    let buttonsCreate = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@2gqewo@save`} type="primary" disabled={false} onClick={this.save}>{getLabel('30986', '保存')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ewap4t@close`} type="ghost" disabled={false} onClick={sendDoc.onlyClose}>{getLabel('309', '关闭')}</Button>,
    ];
    return buttonsCreate;
  };

  update = () => {
    let { sendDoc } = this.props;
    let { odocSendDocDialogForm } = sendDoc;
    odocSendDocDialogForm.updateFields({
      cids: {
        value: '',
        valueSpan: '',
        valueObj: [],
      },
    });
  };

  save = () => {
    let { sendDoc } = this.props;
    let { setReceiveSendUnitInfo, odocSendDocDialogForm, requestId } = sendDoc;
    let param = odocSendDocDialogForm.getFormParams();
    let params = { ...param, requestid: requestId };
    setReceiveSendUnitInfo(params, () => {
      this.update();
    });
  };

  render () {
    const { sendDoc } = this.props;
    const { adSearchForm, loading, ifShowSearchAd, FTPShowRecive, viewcondition, isInnerChange, tableStore, topTab, pagetitle,
      status, onSearch, CHANGE_MODE, rerender, hasRight } = sendDoc;
    let { settedUnit, otherUnit } = toJS(status);
    if (!hasRight) {
      return <OdocNoRightComponent />
    }
    const baseSearchValue = isInnerChange == '0' && CHANGE_MODE == 'FTP' ? adSearchForm.getFormParams().docsubject : adSearchForm.getFormParams().doctitle;
    return (
      <div>
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@cm9kew`} datas={this.getRightMenu()} >
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@54v9dk`}
            title={pagetitle}
            loading={loading}
            icon={<i className="icon-coms-official" />}
            iconBgcolor={'#F14A2D'}
            buttons={this.getTopBtn()}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
          >
            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@xe9s7y`}
              datas={topTab}
              keyParam="viewcondition" // 主键
              countParam="groupid" // 数量
              searchType={['base', 'advanced']}
              selectedKey={viewcondition}
              showSearchAd={ifShowSearchAd}
              // //这里接收的是切换显隐之后相应的bool值
              setShowSearchAd={bool => sendDoc.setStoreAttr('ifShowSearchAd', bool)}
              hideSearchAd={() => sendDoc.setStoreAttr('ifShowSearchAd', false)}
              buttonsAd={this.getSearchBtn()}
              searchsAd={AdSearches(sendDoc, () => onSearch({ behavior: 'changeTab' }))}
              onChange={key => onSearch({ behavior: 'changeTab', viewcondition: key })}
              searchsBaseValue={baseSearchValue}
              onSearchChange={(v) => {
                if (isInnerChange == '1') {
                  adSearchForm.updateFields({ doctitle: { value: v } });
                } else if (CHANGE_MODE != 'FTP') {
                  adSearchForm.updateFields({ doctitle: { value: v } });
                } else {
                  adSearchForm.updateFields({ docsubject: { value: v } });
                }
              }}
              onSearch={() => onSearch({ behavior: 'search' })}
            />

            <WeaTableMobx ecId={`${this && this.props && this.props.ecId || ''}_WeaTableMobx@r29m3c`}
              hasOrder={true}
              needScroll={true}
              comsWeaTableStore={tableStore}
              getColumns={this.getColumns}
              onOperatesClick={(record, index, operate, flag) => sendDoc.onOperatesClick(record, index, operate, flag, this)}
              rowSelection={{
                onChange: sendDoc.selelctRow,
                selectedRowKeys: sendDoc.selectRowId,
              }}
            />
          </WeaTop>
        </WeaRightMenu>

        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@1bvffi`}
          visible={FTPShowRecive}
          title={getLabel('388097', '收文单位信息')}
          icon="icon-coms-official"
          iconBgcolor={'#F14A2D'}
          className="odocSendDocDialog"
          buttons={this.getButton()}
          style={{ width: '785px', height: '500px' }}
          onCancel={sendDoc.onlyClose}
        >
          {this.getSearchs()}

          <Collapse ecId={`${this && this.props && this.props.ecId || ''}_Collapse@601h0l`} title={getLabel('23104', '流程中指定收文单位')} showGroup={true}>
            {settedUnit && (
              <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@byo8e2`}
                columns={settedUnit.columns}
                dataSource={settedUnit.dataSource}
                pagination={false}
              />
            )}
          </Collapse>
          <Collapse ecId={`${this && this.props && this.props.ecId || ''}_Collapse@tj2cj8`} title={getLabel('33565', '其他单位')} showGroup={true}>
            {otherUnit && (
              <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@0y9gs1`}
                columns={otherUnit.columns}
                dataSource={otherUnit.dataSource}
                pagination={false}
              />
            )}
          </Collapse>
        </WeaDialog>

        {/* 收文单位信息弹窗 */}
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@wv8a0w`}
          className="recSendInfo"
          title={getLabel(388097, '收文单位信息')}
          iconBgcolor="#f14a2d"
          icon="icon-coms-official"
          visible={sendDoc.showRecive}
          buttons={this.getDocInfoDialogBtn()}
          onCancel={sendDoc.closeReciveDialog}
          draggable={true}
          maskClosable={false}
          style={{ width: 750, height: 600 }}
        // hasScroll
        >
          <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@d225m7`}
            searchType={['base']}
            onSearch={v => sendDoc.getSendDocinfo(v)}
          />
          <WeaTableMobx ecId={`${this && this.props && this.props.ecId || ''}_WeaTableMobx@mzwfss`}
            comsWeaTableStore={sendDoc.reciveDocUnitTable}
            rowSelection={{
              selectedRowKeys: sendDoc.selectedRowKeys,
              onChange: sendDoc.onUnitRowSelect,
            }}
            onOperatesClick={sendDoc.backout}
            scroll={{ y: 450 }}
          />
        </WeaDialog>

        {/* 撤销公文和作废公文弹窗 */}
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@7bzg2x`}
          title={sendDoc.dialogType == 'backout' && getLabel(388128, '撤销公文') || sendDoc.dialogType == 'invalid' && getLabel(388129, '作废公文')}
          onCancel={sendDoc.hideReasonDialog}
          visible={sendDoc.showReasonDialog}
          style={{ width: 550, height: 212 }}
          maskClosable={false}
          icon="icon-coms-official"
          iconBgcolor="#f14a2d"
          buttons={this.getReasonDialogBtn()}
          className="sendDoc_rejectReason"
          key={rerender}
        >
          <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@8elqee`} ref="scroll" className="rejectReason">
            {sendDoc.dialogType == 'backout' && sendDoc.backoutForm.render({ needTigger: false })}
            {sendDoc.dialogType == 'invalid' && sendDoc.invalidForm.render({ needTigger: false })}
          </WeaNewScroll>
        </WeaDialog>

        {/* 单位浏览按钮弹窗 */}
        <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@s34ucm`}
          ref="browser"
          title={getLabel(388098, '发送其他单位')}
          type="142"
          icon="icon-coms-official"
          iconBgcolor="#f14a2d"
          inputStyle={{ display: 'none' }}
          onChange={sendDoc.resendSubmit}
          isSingle={false}
          // dataParams={{ companyType: isInnerChange }}
          tabs={[
            {
              dataParams: { cmd: 'List' },
              isSearch: true,
              key: '1',
              name: '列表',
              selected: false,
              showOrder: 0,
            },
            {
              dataParams: { cmd: 'Organization' },
              isSearch: false,
              key: '2',
              name: '组织结构',
              selected: false,
              showOrder: 0,
            },
            {
              dataParams: { cmd: 'PublicGroup' },
              isSearch: false,
              key: '3',
              name: '公共组',
              selected: false,
              showOrder: 0,
            },
            {
              dataParams: { cmd: 'PrivateGroup' },
              isSearch: false,
              key: '4',
              name: '私人组',
              selected: false,
              showOrder: 0,
            },
            {
              dataParams: { cmd: 'ExternalUnit', companyType: 1 },
              isSearch: false,
              key: '5',
              name: '外部单位',
              selected: false,
              showOrder: 0,
            },
          ]}
          onClose={() => {
            onSearch({ behavior: 'search' });
            sendDoc.selectRowId = [];
          }}
        />
      </div>
    );
  }

  // 查看收文情况弹窗按钮
  getDocInfoDialogBtn () {
    const store = this.props.sendDoc;
    const { resendSubmit, backout } = store;
    const dialogButtons = [
      <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@c5xhdc@sendOther`}
        title={getLabel(388098, '发送其他单位')}
        type="142"
        customized={true}
        inputStyle={{ width: 200 }}
        onChange={resendSubmit}
        isSingle={false}
        tabs={[
          {
            dataParams: { cmd: 'List' },
            isSearch: true,
            key: '1',
            name: '列表',
            selected: false,
            showOrder: 0,
          },
          {
            dataParams: { cmd: 'Organization' },
            isSearch: false,
            key: '2',
            name: '组织结构',
            selected: false,
            showOrder: 0,
          },
          {
            dataParams: { cmd: 'PublicGroup' },
            isSearch: false,
            key: '3',
            name: '公共组',
            selected: false,
            showOrder: 0,
          },
          {
            dataParams: { cmd: 'PrivateGroup' },
            isSearch: false,
            key: '4',
            name: '私人组',
            selected: false,
            showOrder: 0,
          },
          {
            dataParams: { cmd: 'ExternalUnit', companyType: 1 },
            isSearch: false,
            key: '5',
            name: '外部单位',
            selected: false,
            showOrder: 0,
          },
        ]}
        onClose={() => {
          store.unitArr = [];
          store.unitSelectedRowKeys = [];
        }}
      // dataParams={{ companyType: 1 }}
      >
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@irhbgk@sendOther`} type="primary" className="resendOther" >{getLabel(388098, '发送其他单位')}</Button>
      </WeaBrowser>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@tcuybc@batchUndo`} type="primary" disabled={!(store.unitIdArr.length > 0)} onClick={backout}>{getLabel(388099, '批量撤销')}</Button>,
    ];
    return dialogButtons;
  }

  // 获取拒收原因弹窗按钮
  getReasonDialogBtn () {
    const store = this.props.sendDoc;
    const { hideReasonDialog, dialogType, backoutForm, invalidForm } = store;
    const reasonDialogButton = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@tm5gil@cancel`} type="primary" onClick={hideReasonDialog}>{getLabel(31129, '取消')}</Button>,
    ];
    if (dialogType == 'backout') {
      reasonDialogButton.unshift(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@i6pd3m`} type="primary" onClick={() => this.reasonCheck('backout', backoutForm)}>{getLabel(23757, '撤销')}</Button>);
    } else if (dialogType == 'invalid') {
      reasonDialogButton.unshift(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@u3k117`} type="primary" onClick={() => this.reasonCheck('invalid', invalidForm)}>{getLabel(15358, '作废')}</Button>);
    }
    return reasonDialogButton;
  }

  // 拒收、作废理由 校验
  reasonCheck (type, form) {
    const store = this.props.sendDoc;
    form.validateForm().then((data) => {
      if (data.isValid) {
        if (type == 'backout') {
          store.backoutSubmit();
        } else {
          store.invalidSubmit();
        }
      } else {
        data.showErrors();
      }
    });
  }

  // 修改table列
  getColumns = (columns = []) => columns.map((col) => {
    if (col.dataIndex == 'requestname') {
      return {
        ...col,
        title: col.title,
        className: '',
        render: (text, record) => (
          <a style={{ color: '#4d7ad8' }} onClick={() => this.openWindow(record.requestid, record.workflowid)}>{text}</a>
        ),
      };
    }
    return col;
  })
  // 打开弹窗
  openWindow (id, workflowid) {
    const width = screen.availWidth - 10;
    const height = screen.availHeight - 50;
    let szFeatures = 'top=0,left=0,';
    szFeatures += `width=${width},`;
    szFeatures += `height=${height},`;
    szFeatures += 'directories=no,status=yes,toolbar=no,location=no,';
    szFeatures += 'menubar=no,scrollbars=yes,resizable=yes';
    const url = `/spa/workflow/index_form.jsp#/main/workflow/req?requestid=${id}&_workflowid=${workflowid}&_workflowtype=&isovertime=0`;
    window.open(url, '', szFeatures);
  }

  getTopBtn () {
    const { sendDoc, location } = this.props;
    const { selectRowId, viewcondition, loading, onFTPSend, setMobxState } = sendDoc;
    const isInnerChange = location.query.isInnerChange ? location.query.isInnerChange : '0';
    const disabled = !(toJS(selectRowId).length > 0);
    if (viewcondition == '0') {
      return [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@86xx7d@tatchSend`} type="primary" disabled={disabled} onClick={() => onFTPSend()}>{getLabel('517319', '批量发送')}</Button>];
    } else if (viewcondition == '1' && isInnerChange == '1') {
      return (
        [
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8g9ulg@batchSendOther`} type="primary" disabled={disabled || loading} onClick={() => this.refs.browser.openModal()}>{getLabel('520733', '批量发送其他单位')}</Button>,
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@sfp4ws@batchInvalid`} type="primary" disabled={disabled || loading} onClick={() => setMobxState({ dialogType: 'invalid', showReasonDialog: true })}>{getLabel('520734', '批量作废')}</Button>,
        ]
      );
    } else if (viewcondition == '5') {
      return [];
    } else if (isInnerChange == '1') {
      return ([<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@knf5ac@batchSendOther`} type="primary" disabled={disabled || loading} onClick={() => this.refs.browser.openModal()}>{getLabel('520733', '批量发送其他单位')}</Button>]);
    }
  }

  getRightMenu () {
    const { sendDoc, location } = this.props;
    const { selectRowId, viewcondition, loading, onFTPSend, setMobxState, customSet, onSearch, tableStore } = sendDoc;
    const isInnerChange = location.query.isInnerChange ? location.query.isInnerChange : '0';
    const disabled = !(toJS(selectRowId).length > 0);
    if (viewcondition == 0) {
      return [
        { key: '2', icon: <i className="icon-coms-search" />, content: getLabel('388113', '搜索'), title: getLabel('388113', '搜索'), onClick: () => onSearch({ behavior: 'search' }) },
        { key: '1', icon: <i className="icon-coms-Send-message" />, disabled: disabled || loading, content: getLabel('517319', '批量发送'), title: getLabel('517319', '批量发送'), onClick: () => onFTPSend() },
        { key: '6', icon: <i className="icon-coms-home" />, content: getLabel('32535', '显示列定制'), title: getLabel('32535', '显示列定制'), onClick: () => customSet() },
        { key: '7', icon: <i className="icon-coms-export" />, content: getLabel('28343', '导出Excel'), title: getLabel('28343', '导出Excel'), onClick: () => tableStore.exportAll() },
      ];
    } else if (viewcondition == 1 && isInnerChange == '1') {
      return [
        { key: '3', icon: <i className="icon-coms-search" />, content: getLabel('388113', '搜索'), title: getLabel('388113', '搜索'), onClick: () => onSearch({ behavior: 'search' }) },
        { key: '1', icon: <i className="icon-coms-Send-message" />, disabled: disabled || loading, content: getLabel('520733', '批量发送其他单位'), title: getLabel('520733', '批量发送其他单位'), onClick: () => this.refs.browser.openModal() },
        { key: '2', icon: <i className="icon-coms-Clear" />, disabled: disabled || loading, content: getLabel('520734', '批量作废'), onClick: () => setMobxState({ dialogType: 'invalid', showReasonDialog: true }) },
        { key: '6', icon: <i className="icon-coms-home" />, content: getLabel('32535', '显示列定制'), title: getLabel('32535', '显示列定制'), onClick: () => customSet() },
        { key: '7', icon: <i className="icon-coms-export" />, content: getLabel('28343', '导出Excel'), title: getLabel('28343', '导出Excel'), onClick: () => tableStore.exportAll() },
      ];
    } else if (isInnerChange == '1' && viewcondition != 5) {
      return [
        { key: '3', icon: <i className="icon-coms-search" />, content: getLabel('388113', '搜索'), title: getLabel('388113', '搜索'), onClick: () => onSearch({ behavior: 'search' }) },
        { key: '1', icon: <i className="icon-coms-Send-message" />, disabled: disabled || loading, content: getLabel('520733', '批量发送其他单位'), title: getLabel('520733', '批量发送其他单位'), onClick: () => this.refs.browser.openModal() },
        { key: '6', icon: <i className="icon-coms-home" />, content: getLabel('32535', '显示列定制'), title: getLabel('32535', '显示列定制'), onClick: () => customSet() },
        { key: '7', icon: <i className="icon-coms-export" />, content: getLabel('28343', '导出Excel'), title: getLabel('28343', '导出Excel'), onClick: () => tableStore.exportAll() },
      ];
    }
    return [
      { key: '3', icon: <i className="icon-coms-search" />, content: getLabel('388113', '搜索'), title: getLabel('388113', '搜索'), onClick: () => onSearch({ behavior: 'search' }) },
      { key: '6', icon: <i className="icon-coms-home" />, content: getLabel('32535', '显示列定制'), title: getLabel('32535', '显示列定制'), onClick: () => customSet() },
      { key: '7', icon: <i className="icon-coms-export" />, content: getLabel('28343', '导出Excel'), title: getLabel('28343', '导出Excel'), onClick: () => tableStore.exportAll() },
    ];
  }

  getSearchBtn () {
    const { sendDoc } = this.props;
    const { viewconditiondomkey, adSearchForm, setStoreAttr, onSearch } = sendDoc;
    return [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@b7tc6q@search`} type="primary" onClick={() => onSearch({ behavior: 'search', viewconditiondomkey })}>{getLabel('388113', '搜索')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@10itnl@reset`} type="ghost" onClick={() => adSearchForm.reset()}>{getLabel('2022', '重置')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@i7ui4p@cancel`} type="ghost" onClick={() => setStoreAttr('ifShowSearchAd', false)}>{getLabel('31129', '取消')}</Button>,
    ];
  }
}

export default SendDoc;
